package io.mft.commons.multithreading.worker;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * 工作任务分发管理
 * 
 * @描述:
 * @版权: Copyright (c) 2015
 * @公司: 思迪科技
 * @作者:胡常建
 * @版本: 1.0
 * @创建日期: 2015年5月17日
 * @创建时间: 上午9:40:00
 */
public class WorkManager{
	static Logger logger=LoggerFactory.getLogger(WorkManager.class);

	private ThreadPoolTaskExecutor poolTaskExecutor;
	private int contextThreadNumber;
	private static ConcurrentHashMap<String, WorkManager> workManagers=new ConcurrentHashMap<String, WorkManager>();
	//private final LinkedBlockingQueue<Object> queue;
	private static String DEFAULT_MANAGERID=WorkManager.class.getName();
	private String note;
	private int capacity=Integer.MAX_VALUE;
	public ThreadPoolTaskExecutor getPoolTaskExecutor() {
		return poolTaskExecutor;
	}
	
	/**
	 * 获取默认工作管理器
	 * @描述：
	 * @作者：胡常建
	 * @时间：2015年5月17日 下午2:04:41
	 * @return
	 */
	public static WorkManager getManager(){
		int maxIdleWorkerNumber=8;
		int contextThreadNumber=8;
		return getManager(DEFAULT_MANAGERID,contextThreadNumber,maxIdleWorkerNumber);
	}
	
	public boolean isExecuteDone() {
		int unDoning=poolTaskExecutor.getThreadPoolExecutor().getQueue().size();
		int doning=poolTaskExecutor.getThreadPoolExecutor().getActiveCount();
		long completedTaskCount=poolTaskExecutor.getThreadPoolExecutor().getCompletedTaskCount();
		long taskCount=poolTaskExecutor.getThreadPoolExecutor().getTaskCount();
		boolean done=unDoning==0&&doning==0&&completedTaskCount==taskCount;
		return done;
	}
	/**
	 * 根据工作管理器Id获取一个实例
	 * @描述：
	 * @作者：胡常建
	 * @时间：2015年5月17日 下午2:04:07
	 * @param managerId
	 * @return
	 */
	public static WorkManager getManager(String managerId,int contextThreadNumber,int maxIdleNumber,int capacity){
		if (workManagers.containsKey(managerId)) {
			return workManagers.get(managerId);
		}
		synchronized (workManagers) {
			if (!workManagers.containsKey(managerId)) {
				WorkManager manager=new WorkManager(managerId,contextThreadNumber,maxIdleNumber,capacity);
				workManagers.put(managerId, manager);
			}
		}
		return workManagers.get(managerId);
	}
	public static WorkManager getManager(String managerId,int contextThreadNumber,int maxIdleNumber) {
		return getManager(managerId, contextThreadNumber, maxIdleNumber, Integer.MAX_VALUE);
	}
	private String id;
	public String getId() {
		return id;
	}
	private WorkManager(String id,int contextThreadNumber,int maxIdleWorkerNumber,int capacity){
		 this.contextThreadNumber=contextThreadNumber;
		 this.id=id;
		 this.note=id;
		 this.capacity=capacity;
		 poolTaskExecutor=ThreadPoolManager.create(id, contextThreadNumber, contextThreadNumber,capacity);
		// debug(id+"初始化线程池成功!线程池容量："+this.contextThreadNumber);
	}
	public int getCapacity() {
		return capacity;
	}
	/**
	 * 接收要处理的任务
	 * @描述：
	 * @作者：胡常建
	 * @时间：2015年5月17日 上午9:52:22
	 * @param handler
	 */
    public void acceptWork(Work work) {
    	try {
        	WorkRunner workRunner=new WorkRunner(work,this);
        	poolTaskExecutor.submit(workRunner);
		} catch (Exception e) {
			logger.error("",e);
		}

	}
    public Future<?> acceptFutureWork(Work work) {
    	try {
        	WorkRunner workRunner=new WorkRunner(work,this);
        	return poolTaskExecutor.submit(workRunner);
		} catch (Exception e) {
			logger.error("",e);
			return null;
		}

	}
    public void setNote(String note) {
		this.note = note;
	}
    public String getNote() {
		return note;
	}
	public void stop() {
		poolTaskExecutor.shutdown();
		workManagers.remove(id);
	}
	public int workNumber() {
		return poolTaskExecutor.getThreadPoolExecutor().getActiveCount();
	}
	
	
	public int getContextThreadNumber() {
		return contextThreadNumber;
	}
}
